<template>
  <div class="page-wrap">
    <el-upload
      ref="upload"
      class="upload-demo"
      drag
      :multiple="false"
      :limit="1"
      :on-exceed="exceed"
      :show-file-list="false"
      accept=".xlsx"
      :on-progress="handleUploadProgress"
      name="multipartFile"
      :on-success="success"
      :on-error="error"
      :before-upload="handleBeforeUpload"
      :action="action"
      :headers="headers"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">拖拽表格到此或点击上传</div>
      <div class="el-upload__btn">
        <el-button type="primary">点击上传</el-button>
        <el-button type="info" @click.stop="getVisitCustomer"
          >探马回传</el-button
        >
      </div>
      <div
        class="progress-container"
        style="margin-top: 22px"
        v-show="showUploadProgress"
      >
        <hk-progress
          :width="400"
          :progress="uploadPercentage"
          :strokeWidth="10"
          :showInfo="true"
        ></hk-progress>
      </div>
      <div class="el-upload__tip" slot="tip">
        <p>文件类型为excel，一次只能上传1个文件</p>
        <p>
          需包含字段：日期、时间、企业名称、企业地址、指派人员、指派时间（上午、下午、全天）时间需按24小时制填写，以便系统区分上下午
        </p>
      </div>
    </el-upload>
    <div class="dialog-container">
      <el-dialog
        class="my-dialog"
        title="选择"
        width="600px"
        :visible.sync="dialogVisible"
        destroy-on-close
      >
        <div class="form-box">
          <!-- <p class="date-time">
            派单日期： {{ formatDate(nextDate, "yyyy/MM/dd") }}
          </p> -->
          <el-form
            :model="paramsAll"
            ref="adminForm"
            :rules="rules"
            size="s米糕"
            label-width="100px"
          >
            <el-form-item label="日期：">
              <el-date-picker
                v-model="nextDateArr"
                type="datetimerange"
                align="right"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="地区：" prop="cityValue.values">
              <el-select
                v-model="paramsAll.cityValue.values"
                multiple
                clearable
                filterable
                collapse-tags
                placeholder="请选择城市"
              >
                <el-option
                  v-for="item in cityOptions ? cityOptions.options : []"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="类型：" prop="postValue">
              <el-radio-group v-model="paramsAll.postValue">
                <el-radio :label="0">首访</el-radio>
                <el-radio :label="1">后道</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('adminForm')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import { getToken } from "@/utils/auth";
import hkProgress from "@/components/hk-progress";
import { visitCustomer, visitCustomerSearch } from "@/api/dispatch";
import { formatDate } from "@/utils/date";
import minxins from "./mixins";
import rules from "./rules";
import { mapState } from "vuex";
export default {
  name: "uploadInformation",
  mixins: [minxins],
  data() {
    return {
      uploadPercentage: 0,
      showUploadProgress: false,
      action: "",
      headers: {
        Authorization: "",
        type: 0,
      },
      dialogVisible: false,
      // 筛选数组
      options: [],
      formatDate,
      rules,
    };
  },
  components: {
    hkProgress,
  },
  created() {
    this.headers.Authorization = getToken() || "";
    this.action = process.env.VUE_APP_SERVER + "/upload/uploadXlsx";
    this.getOptions();
    let tanmaParams = this.$store.state.tanma || {};
    const { city, date, post } = tanmaParams;
    this.paramsAll.cityValue.values = city || "";
    this.paramsAll.postValue = post || 0;
    this.nextDateArr = date || [];
    // this.nextDates();
  },
  methods: {
    // 获取筛选条件
    getOptions() {
      visitCustomerSearch().then((res) => {
        this.optionsAll = res.data.data;
        this.cityOptions = this.filterOptions(this.optionsAll, 95560);
        localStorage.setItem("cityOptions", JSON.stringify(this.cityOptions));
      });
    },

    submitForm(form) {
      this.$refs[form].validate((valid) => {
        console.log(valid);
        if (valid) {
          this.submitForms();
        } else {
          return false;
        }
      });
    },

    submitForms() {
      let params = {};
      let params1 = {};
      const post = [
        // 前道
        {
          conditionItems: [
            this.paramsAll.cityValue,
            {
              name: 98173,
              op: 6,
              values: this.nextDateArr,
            },
            {
              name: 99808,
              op: 2,
              values: [0],
            },
          ],
        },

        {
          // 前道 Plus
          conditionItems: [
            this.paramsAll.cityValue,
            {
              name: 137805, // 首访 Plus
              op: 5, // 不为空
              values: [],
            },
            {
              name: 137803,
              op: 6,
              values: this.nextDateArr,
            },
          ],
        },

        {
          // 后道
          conditionItems: [
            {
              name: 130228,
              op: 6,
              values: this.nextDateArr,
            },
            this.paramsAll.cityValue,
            // {
            //   name: 130418,
            //   op: 2,
            //   values: [1],
            // },
          ],
        },
      ];

      let allParams = [];

      params = JSON.parse(JSON.stringify(this.optionsParams));

      console.log("params", params);

      if (this.paramsAll.postValue === 0) {
        params.conditions.conditionItems = post[0].conditionItems;

        let second = {
          conditions: {
            conditionItems: post[1].conditionItems,
            conditionOp: 0,
          },
          pageNo: params.pageNo,
          pageSize: params.pageSize,
        };

        console.log("second", second);

        allParams.push(params);

        allParams.push(second);
      } else {
        params.conditions.conditionItems = post[2].conditionItems;
        allParams.push(Object.assign({}, params));
        // params1.conditions.conditionItems = post[2].conditionItems;
        // allParams.push(Object.assign({}, params1));
      }
      let stateParams = {
        post: this.paramsAll.postValue || 0,
        city: this.paramsAll.cityValue.values || [],
        date: this.nextDateArr || [],
      };

      this.$store.commit("SET_TANMA", stateParams);
      visitCustomer(allParams).then((res) => {
        this.dialogVisible = false;
        this.$store.commit("SET_ISTANMA", true);
        this.$store.commit("ERROR_CLIENT_LIST", res.data);
        setTimeout(() => {
          this.$router.push({
            path: "/dispatch/dispatchList",
            query: {
              fileName: "探马获取",
              time: new Date(this.nextDateArr[0]).getTime(),
            },
          });
        }, 600);
      });
    },
    // 探马获取客户
    getVisitCustomer() {
      this.dialogVisible = true;
    },

    exceed(e) {
      Message.error("单次只能上传1个文件");
    },
    handleUploadProgress(event, file, fileList) {
      this.uploadPercentage = 0;
      this.showUploadProgress = true;
      this.uploadPercentage = event.percent.toFixed(2) || 0;
      if (this.uploadPercentage === 100) {
        setTimeout(() => {
          this.showUploadProgress = false;
          this.uploadPercentage = 0;
        }, 1500);
      }
    },
    handleBeforeUpload(file) {
      const fileType = file.type;
      const allowedTypes = [
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ];
      const allowedExtensions = [".xlsx"];

      // 文件类型检查
      if (
        !allowedTypes.includes(fileType) &&
        !allowedExtensions.includes(file.name.split(".").pop())
      ) {
        Message.error("请上传xlsx文件类型");
        return false; // 阻止文件上传
      }

      return true; // 允许文件上传
    },
    success(e, file) {
      if (e.resultCode !== 200) {
        Message.error(e.message);
        this.$refs.upload.clearFiles();

        setTimeout(() => {
          this.showUploadProgress = false;
          this.uploadPercentage = 0;
        }, 500);
      } else {
        this.$store.commit("SET_ISTANMA", false);

        setTimeout(() => {
          this.$router.push({
            path: "/dispatch/dispatchList",
            query: {
              fileName: file.name,
            },
          });
        }, 1000);
      }
      this.$refs.upload.clearFiles();
    },
    error(e) {
      this.$refs.upload.clearFiles();
      Message.error("上传失败");
      setTimeout(() => {
        this.showUploadProgress = false;
        this.uploadPercentage = 0;
      }, 500);
    },
  },

  computed: {
    ...mapState["tanma"],
  },
};
</script>

<style lang="scss" scoped>
.page-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 80px;
}

.el-upload__btn {
  margin-top: 10px;
}
.upload-demo {
  width: 80%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.upload-demo :deep(.el-upload-dragger) {
  width: 100%;
  height: 60vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.upload-demo :deep(.el-upload) {
  width: 100%;
  height: 100%;
}
.el-upload__tip {
  color: yellowgreen;
  font-size: 16px;
}

.form-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;

  .el-form {
    width: max-content;
  }
}

.date-time {
  font-size: 18px;
  padding: 0 0 20px 0;
}
</style>